package com.tianqu.tms.core.taglib;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;

import com.tianqu.tms.core.base.TmsAction;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.MenuTagUtil;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.TmsConstants;

/**
 * menu html的生成
 *
 * @author liugang
 */
public class MenuTag extends MenuTagSupport {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    /**
     * 换行
     */
    protected static final String CRLF = System.getProperty("line.separator");

    /**
     * funcId
     */
    private String funcId;
    public static MenuBean rootMenuBean;
    private MenuBean currentMenuBean;

	
	/*----------------------------- Protected methods ----------------------------*/

    /**
     * tag处理开始
     */
    public int doStartTag() throws JspException {
        // zhk liu.xingya start
        // 临时菜单,有限在request读出
//		rootMenuBean =(MenuBean) pageContext.getServletContext().getAttribute(TmsConstants.MENU_VO_KEY);
        rootMenuBean = (MenuBean) pageContext.getRequest().getAttribute(TmsConstants.MENU_VO_KEY);
        if (rootMenuBean != null) {
            funcId = pageContext.getRequest().getParameter("funcId");
        } else {
            rootMenuBean = (MenuBean) pageContext.getServletContext().getAttribute(TmsConstants.MENU_VO_KEY);
        }
        // zhk liu.xingya end
        if (funcId == null) {
            throw new JspTagException("funcId is required");
        }
        if (rootMenuBean == null) {
            throw new JspTagException("Cannot find MenuBean");
        }
        currentMenuBean = rootMenuBean.getMenuVO(funcId);
        JspWriter out = null;
        try {
            out = pageContext.getOut();
            out.print(this.buildHtml(rootMenuBean));
        } catch (IOException e) {
            throw new JspException("across:" + e.toString());
        }

        return EVAL_BODY_INCLUDE;
    }

    /**
     *
     */
    public int doEndTag() throws JspException {
        return EVAL_PAGE;
    }

    /**
     * 生成menu html
     *
     * @param menuBean
     * @return
     * @throws JspException
     */
    protected String buildHtml(MenuBean menuBean) throws JspException {
        StringBuffer sb = new StringBuffer();
        sb.append("<div class=\"topLogo\">");
        sb.append("<a href=\"menu.tq\">");
        sb.append("<img src=\"" + TmsConstants.STATIC_CONTEXT_ROOT + "/style/images/logo.jpg\" /></a></div>");
        sb.append("<div class=\"userLogin\">");
        sb.append("<span>");
		/*
		 * 获得用户名
		 */
        //获得menu对象
        TmsUserProfile userprofile =
                (TmsUserProfile) pageContext.getRequest().getAttribute(
                        TmsAction.USER_PROFILE_KEY);
        //menu对象是空
        if (userprofile == null) {
            throw new JspTagException("Cannot find UserProfile");
        }
        sb.append("当前用户：" + userprofile.getRealName());
        sb.append("</span>");
        sb.append("<span><a href=\"" + TmsConstants.LOGINPAGE + "\">退出</a></span>");
        sb.append("</div>");

        sb.append("<div id=\"left-nav\">");
        sb.append(CRLF);
        sb.append("<div class=\"top-level\">");
        sb.append(CRLF);

        this.buildNavigation(menuBean, sb);
        sb.append("</div>");
        sb.append(CRLF);
        sb.append("</div>");
        sb.append(CRLF);
        return sb.toString();
    }

    /**
     * 格式如下：
     *
     * @param menuBean
     * @param sb
     */
    protected void buildNavigation(MenuBean menuBean, StringBuffer sb) {
        String functionId = menuBean.getFunctionId();
        boolean isSelected = this.funcId.equals(functionId);
        String navigationName = menuBean.getMenuName();
        String uri = menuBean.getTargetUri();
        int level = menuBean.getLevel();
        switch (level) {
            case 0:
                //==============================================================
                //     第0层
                //==============================================================
                break;
            case 1:
                //==============================================================
                //     第一层
                //==============================================================
                // 判断是否有权限
                if (hasViewCompetence(menuBean)) {
                    if (menuBean.isParent(currentMenuBean)) {
                        createLink(sb, navigationName, uri, isSelected, true, 1);
                    } else {
                        createLink(sb, navigationName, uri, isSelected, false, 1);
                    }
                }
                break;
            case 2:
                //==============================================================
                //     第二层
                //==============================================================
                // 判断是否有权限
                if (hasViewCompetence(menuBean)) {
                    createLink(sb, navigationName, uri, isSelected, false, 2);
                    sb.append(CRLF);
                }
                break;
            default:
                break;
        }

        //======================================================================
        //     其子菜单加载
        //======================================================================
        if (hasViewCompetence(menuBean)) {
            if (level == 0 || isSelected || menuBean.isParent(currentMenuBean)) {
                List children = menuBean.getChildrenList();

                if (children != null && children.size() > 0) {
                    if (level == 1) sb.append("<div class=\"second-level\">");
                    Iterator childrenIt = children.iterator();
                    while (childrenIt.hasNext()) {
                        MenuBean targetBean = (MenuBean) childrenIt.next();
                        buildNavigation(targetBean, sb);
                    }
                    if (level == 1) sb.append("</div>");
                }
            }
        }
        sb.append(CRLF);
    }

    /**
     * 生成link
     *
     * @param html
     * @param navigationName
     * @param uri
     * @param isSelected
     * @param childSelected
     * @return
     */
    private StringBuffer createLink(StringBuffer html, String navigationName,
                                    String uri, boolean isSelected, boolean childSelected, int level) {
        html.append("<a href=\"");
        html.append(uri);
        html.append("\" ");
        if (isSelected) {
            html.append(" class=\"active\"");
        }
        html.append(">");
        html.append(navigationName);
        html.append("</a>");
        html.append(CRLF);

        return html;
    }

    public String getFuncId() {
        return funcId;
    }

    public void setFuncId(String funcId) {
        this.funcId = funcId;
    }
}